package com.huan.social.weixin.connect;

import com.huan.social.weixin.api.Weixin;
import org.springframework.social.connect.ApiAdapter;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.support.OAuth2Connection;
import org.springframework.social.connect.support.OAuth2ConnectionFactory;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2ServiceProvider;

/**
 * 微信 的连接工厂
 *
 * @author huan.fu
 * @date 2018/9/27 - 11:36
 */
public class WeixinConnectionFatory extends OAuth2ConnectionFactory<Weixin> {

	public WeixinConnectionFatory(String providerId, String clientId, String clientSecret, String userInfoUrl, String authorizeUrl, String accessTokenUrl, String refreshTokenUrl) {
		super(
				providerId,
				new WeixinServiceProvider(clientId, clientSecret, userInfoUrl, authorizeUrl, accessTokenUrl, refreshTokenUrl),
				new WeixinAdapter()
		);
	}

	/**
	 * 抽取providerUserId,由于微信的providerUserId(openId)是在accessGrant中，因此此处需要返回
	 *
	 * @param accessGrant
	 * @return
	 */
	@Override
	protected String extractProviderUserId(AccessGrant accessGrant) {
		if (accessGrant instanceof WeixinAccessGrant) {
			return ((WeixinAccessGrant) accessGrant).getOpenId();
		}
		return null;
	}

	/**
	 * 创建连接
	 *
	 * @param accessGrant
	 * @return
	 */
	@Override
	public Connection<Weixin> createConnection(AccessGrant accessGrant) {
		return new OAuth2Connection<>(getProviderId(), extractProviderUserId(accessGrant),
				accessGrant.getAccessToken(), accessGrant.getRefreshToken(), accessGrant.getExpireTime(),
				getOAuth2ServiceProvider(), getApiAdapter(extractProviderUserId(accessGrant)));
	}


	@Override
	public Connection<Weixin> createConnection(ConnectionData data) {
		return new OAuth2Connection<>(data, getOAuth2ServiceProvider(), getApiAdapter(data.getProviderUserId()));
	}

	protected ApiAdapter<Weixin> getApiAdapter(String providerUserId) {
		return new WeixinAdapter(providerUserId);
	}

	protected OAuth2ServiceProvider<Weixin> getOAuth2ServiceProvider() {
		return (OAuth2ServiceProvider<Weixin>) getServiceProvider();
	}
}
